package com.chenfan.magic.tags.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chenfan.magic.base.Kv;
import com.chenfan.magic.constant.RuntimeConstant;
import com.chenfan.magic.entity.MQLModel;
import com.chenfan.magic.entity.TTLDetailModel;
import com.chenfan.magic.entity.TTLModel;
import com.chenfan.magic.resolver._MainResolver;
import com.chenfan.magic.tags.TagValidate;
import com.chenfan.magic.utils.FastJsonKit;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * template 标签处理器
 *
 * @author  周夕
 * @date 2020-02-26 18:21
 */
@Component
@AllArgsConstructor
public class TagValidateHandler {

    /**
     * 执行入口
     *
     * @param mqlModel
     * @param key
     * @return
     */
    public boolean execute(
            MQLModel mqlModel,
            Map<String, Object> idcRuntimePool,
            String key,
            Map<String, Object> paramMap,
            Map<String, Object> resMap,
            Map<String, Object> eofMap,
            Map<String, Object> resolveMap,
            Map<String, Object> attributeMap,
            Kv kv,
            TTLModel ttlModel
    ) {
        TTLDetailModel ttlDetailModel = new TTLDetailModel();
        String prefixKey = TagValidate.tagNames + "#" + key;
        ttlDetailModel.start(prefixKey);
        TagValidate validateModel = mqlModel.getValidate(key, idcRuntimePool, paramMap, attributeMap);
        kv.set(RuntimeConstant.RUNTIME_EXECUTE_VAR_KEY_PREFIXKEY, prefixKey);
        kv.set(RuntimeConstant.RUNTIME_EXECUTE_VAR_KEY_RESPOND, validateModel.getRespond());
        kv.set(RuntimeConstant.RUNTIME_EXECUTE_VAR_KEY_RESULTKEY, validateModel.getResultKey());
        Map<String, Object> res = Maps.newHashMap();
        String result = "";
        //防止引用检测
        String json = JSON.toJSONString(paramMap, SerializerFeature.DisableCircularReferenceDetect);
        Map<String, Object> pm = FastJsonKit.jsonstring2Map(json);
        pm.remove("#params");
        pm.remove("#context");

        result = new _MainResolver().resolveScope(idcRuntimePool, ttlModel, prefixKey, validateModel, paramMap);
        resolveMap.put(validateModel.getResultKey(), result);
        result = result.replace("\t", "").replace("\n", "");
        res.put(validateModel.getResultKey(), result);

        res.put("#params", pm);
        res.put("#context", result);
        resMap.put(prefixKey, res);
        paramMap.putAll(attributeMap);
        paramMap.putAll(res);
        ttlDetailModel.end();

        ttlModel.getExecuter().put(ttlDetailModel.end());
        return true;
    }

}
